package aop;

import entity.MyResult;
import entity.Resource;
import entity.Role;
import org.aspectj.bridge.MessageWriter;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import java.util.List;
import java.util.logging.Handler;

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod methodHandle= (HandlerMethod) handler;
        //控制层方法对象
        Method method = methodHandle.getMethod();
        //获取控制层方法上的注解
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        if (annotation==null){
            return true;//没有注解，不需要做权限控制
        }
        //获取方法需要的权限值
        String permission = annotation.value();
        //获取权限的信息
        Role role =(Role) request.getSession().getAttribute("role");
        List<Resource> resourceList=role.getResourceList();
        for (Resource resource:resourceList){
            //如果权限值匹配，则放行
            if (permission.equals((resource.getPermission()))){
                return true;

            }
        }
        //判断是否是ajax请求
        String header=request.getHeader("X-Requested-with");
        if (header!=null&& header.equalsIgnoreCase("XMLHttpRequest")){
            //封装一个响应对象
            MyResult<String> result=new MyResult<>(403,"没有权限操作");
            response.setContentType("application/json;charset=UTF-8");
            //通过Jackson，将对象转换成json字符串
            ObjectMapper objectMapper=new ObjectMapper();
            String s=objectMapper.writeValueAsString(result);
            //通过response响应数据
            response.getWriter().write(s);
            return false;
        }
        //跳转到没有权限的页面
        response.sendRedirect(request.getContextPath()+"/403.jsp");
        return false;
    }
}
